package com.link.base.tencent.corpwx.externalcontact.service;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import com.link.base.tencent.corpwx.externalcontact.dao.mybatis.mapper.ExternalFollowUserMapper;
import com.link.base.tencent.corpwx.externalcontact.model.ExternalFollowUser;
import com.link.core.basic.dao.mapper.BasicMapper;
import com.link.core.basic.service.BasicServiceImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 外部联系人-跟进人 
 *
 * @author 欧阳振强
 * @date 2020-01-02 15:39:55.0
 */
@Service
public class ExternalFollowUserServiceImpl extends BasicServiceImpl<ExternalFollowUser> implements ExternalFollowUserService {

    @Resource
    private ExternalFollowUserMapper externalFollowUserMapper;
    @Resource
    private ExternalFollowTagService externalFollowTagService;
    
    @Override
    public BasicMapper<ExternalFollowUser> getBasicMapper() {
        return externalFollowUserMapper;
    }

    @Override
    public List<ExternalFollowUser> listExternalFollowUserByHeadId(Long headId) throws Exception {
        ExternalFollowUser externalFollowUser = new ExternalFollowUser();
        externalFollowUser.setHeadId(headId);
        return externalFollowUserMapper.listExternalFollowUserByHeadId(externalFollowUser);
    }

    @Override
    public List<ExternalFollowUser> opExternalFollowUserList(List<ExternalFollowUser> apiList, List<ExternalFollowUser> linkList) throws Exception {
        List<ExternalFollowUser> externalFollowUserList = new ArrayList<>();
        if (apiList == null) {
            apiList = new ArrayList<>();
        }
        if (linkList == null) {
            linkList = new ArrayList<>();
        }
        Map<String, ExternalFollowUser> apiListMap =
            apiList.stream().collect(Collectors.toMap(item -> item.getUserId(), item -> item));
        Map<String, ExternalFollowUser> linkListMap =
            linkList.stream().collect(Collectors.toMap(item -> item.getUserId(), item -> item));
        for (ExternalFollowUser apiItem: apiList) {
            ExternalFollowUser temp = linkListMap.get(apiItem.getUserId());
            if (temp == null) {
                apiItem.setOp("add");
            } else {
                apiItem.setHeadId(temp.getHeadId());
                apiItem.setId(temp.getId());
                apiItem.setOp("update");
                // 重新设置需要更新的跟进人下的待操作标签组
                apiItem.setTagList(externalFollowTagService.opExternalFollowTagList(apiItem.getTagList(), temp.getTagList()));
            }
            externalFollowUserList.add(apiItem);
        }
        for (ExternalFollowUser linkItem: linkList) {
            if (apiListMap.get(linkItem.getUserId()) == null) {
                linkItem.setOp("del");
                externalFollowUserList.add(linkItem);
            }
        }
        return externalFollowUserList;
    }
}